import request from "./request.js"

export function requestByUrl(url,method="get",data={}) {
	let p = {
		url,
		method
	}
	if(method == 'get') {
		p['params'] = data
	} else {
		p['data'] = data
	}
	return request(p)
}

export function mergeArray(data) {
	let arr = []
	data.map(ele=>{
		arr.push(...ele.elements)
	})
	return arr
}

/**
 * 检查对象数组中是否存在目标对象
 * @param arrayData 被检查数组
 * @param obj	目标对象
 */
export function existObj(arrayData,obj,key) {
	let flag = false
	arrayData.map(item=>{
		if (item[key] == obj[key]) {
			flag = true
		}
	})
	return flag
}

// 产品列表转化为树表
export function productToTree(lists) {
	const data = JSON.parse(JSON.stringify(lists))
	let tree = []
	let map = {}
	let materialMap = {}
	let specMap = {}
	data.map(item=>{
		if (!map[item.name]) {
			map[item.name] = {
				'label': item.name,
				'value': item.name,
				'children':[]
			}
		}
		let key1 = `${item.name}_${item.spec}`
		if (!specMap[key1]) {
			specMap[key1] = {
				'label': item.spec,
				'value': item.spec,
				'children': []
			}
		}
		let key = `${item.name}_${item.spec}_${item.material}`
		if (!materialMap[key]) {
			materialMap[key] = {
				'label': item.material,
				'value': item.id,
			}
		}
	})
	data.map(item=> {
		let key = `${item.name}_${item.spec}_${item.material}`
		let key1 = `${item.name}_${item.spec}`
		if (!existObj(specMap[key1].children,materialMap[key],'value')) {
			specMap[key1].children.push(materialMap[key])
		}
		if (!existObj(map[item.name].children,specMap[key1],'value')) {
			map[item.name].children.push(specMap[key1])
		}
	})
	Object.keys(map).forEach(key=>{
		tree.push(map[key])
	})
	return tree
}

export function compare(prop) {
	return function (obj1,obj2) {
		let val1 = obj1[prop]
		let val2 = obj2[prop]
		if (val1 < val2) {
			return -1;
		} else if (val1 > val2) {
			return 1
		} else {
			return 0
		}
	}
}
// 递归查询数组
export function recursion(origin,key,callback) {
	let result = []
	function innerRecursion(origin,key,callback) {
		origin.forEach(item=>{
			if (item[key] && item[key].length > 0) {
				if (callback(item)) {
					result.push(item)
				}
				innerRecursion(item[key],key,callback)
			} else {
				if (callback(item)) {
					result.push(item)
				}
			}
		})
	}
	innerRecursion(origin,key,callback)
	return result
}

